package com.shoujifeng.snowmusic.player;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.shoujifeng.snowmusic.player.R;
import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.entity.AnimaAccess;
import com.shoujifeng.snowmusic.entity.Mp3Info;
import com.shoujifeng.snowmusic.player.http.GlobalValue;
import com.shoujifeng.snowmusic.player.http.ServerAccess;
import com.shoujifeng.snowmusic.player.interfaces.MoreInterface;
import com.shoujifeng.snowmusic.player.utils.MediaUtil;
import com.shoujifeng.snowmusic.player.utils.MusicPlayer;

/**
 * 本地音乐列表
 * @author luo
 *
 */
public class NativeMusicActivity extends Activity{
	
	public ListView listView;
	private MyAdapter mAdapter;
	private List<Mp3Info> mp3Infos;
	private LinearLayout nativeEditLay;
	private boolean mSetManageLayView = false;
	private View lineLayout;
	private LinearLayout musicMenuPlay;
	public static List<HashMap<String,Object>> mp3list;
	
	private static String sdState = Environment.getExternalStorageState();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.native_music);
		init();
	}
	
	public void init() {
		
		listView = (ListView) findViewById(R.id.native_music_list);
		listView.setDivider(null);
		
		lineLayout = LayoutInflater.from(NativeMusicActivity.this).inflate(R.layout.line_layout, null);
		listView.addFooterView(lineLayout);
		listView.setOnItemClickListener(itemClickListener);
		
		nativeEditLay = (LinearLayout) findViewById(R.id.native_edit_lay);
		nativeEditLay.setOnClickListener(onClickListener);
		
		setListAdpter();
		musicMenuPlay = (LinearLayout) findViewById(R.id.music_menu_play);
		musicMenuPlay.setOnClickListener(onClickListener);
		
	}
	public void setListAdpter() {
		
		MediaUtil mediaUtil 	= new MediaUtil();
		mp3Infos 				= mediaUtil.getMp3Infos(NativeMusicActivity.this);
		mp3list 				= new ArrayList<HashMap<String,Object>>();
		
		for(int i = 0 ;i<mp3Infos.size();i++){
			
			HashMap<String,Object> map = new HashMap<String, Object>();
			
			map.put("album", mp3Infos.get(i).getAlbum());
			map.put("Artist", mp3Infos.get(i).getArtist());
			map.put("title", mp3Infos.get(i).getTitle());
			map.put("url", mp3Infos.get(i).getUrl());
			map.put("duration", mp3Infos.get(i).getDuration()+"");
			map.put("size", mp3Infos.get(i).getSize()+"");
			
			mp3list.add(map);
		}
		MusicPlayer.musicInfos = mp3Infos;
		
		mAdapter = new MyAdapter(this, mp3list, R.layout.native_music_list,
									new String[] { "title", "Artist" }, 
									new int[] { R.id.musicName, R.id.playerName });
		
		listView.setAdapter(mAdapter);
	}
	
	private View.OnClickListener onClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.native_edit_lay:
				Intent intent = new Intent(NativeMusicActivity.this,EditListMusicActivty.class);
				intent.putExtra("activityName", "NativeMusicActivity");
				startActivity(intent);
				
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
				break;
			case R.id.music_menu_play:{
				MusicPlayerActivity.isOnline = false;
				Intent  intent2 = new Intent(NativeMusicActivity.this, MusicPlayerActivity.class);
				MusicPlayer musicPlayer = new MusicPlayer(NativeMusicActivity.this);
				List<Mp3Info> mp3Infos =musicPlayer.getMp3Infos(NativeMusicActivity.this);
				MusicPlayer.musicInfos = mp3Infos;
				Random random = new Random();
				int s = random.nextInt(mp3Infos.size())%(mp3Infos.size()-0+1) + 0;
				MusicPlayer.position  = s;
				startActivity(intent2);
				overridePendingTransition(R.anim.bottom_in,android.R.anim.fade_out);
			}	
			break;
			
			default:
				break;
			}
			
		}
	};
	private OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view, int position,
				long arg3) {
			// 此处相应ListView 项按下
			// pos是按下项的ID
			MusicPlayerActivity.isOnline = false;
			Intent intent = new Intent(NativeMusicActivity.this, MusicPlayerActivity.class);
			Mp3Info mp3Info = mp3Infos.get(position);
			String url = mp3Info.getUrl();
	        intent.putExtra("url", url);         
	        MusicPlayer.position = position; 
	        MusicPlayer.MUSCI_MSG =1;
			startActivity(intent);
			overridePendingTransition(R.anim.bottom_in,android.R.anim.fade_out);
		}
	};
	
	private class MyAdapter extends BaseAdapter {
		int count = 0;
		private List<HashMap<String, Object>> mItemList;
		//上一次点击的MoreView
		private View mLastMore;
		private int layout;
		private String[] mKeys;
		private int[] ids;
		private Context mContext;
		//点击回调
		private MoreInterface moreInterface;
		
		public MyAdapter(Context context,
				List<HashMap<String, Object>> arrayList, int songMenuList,
				String[] strings, int[] is) {
			
			//super(context, arrayList, songMenuList, strings, is);
			mItemList = arrayList;
			if (arrayList == null) {
				count = 0;
			} else {
				count = arrayList.size();
			}
			// TODO Auto-generated constructor stub
			
			layout = songMenuList;
			mKeys = strings;
			ids = is;
			mContext = context;
			
			mLastMore = null;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mItemList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mItemList.size();
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			
			convertView = LayoutInflater.from(mContext).inflate(layout, null);
			
			HashMap<String, Object> map = mItemList.get(position);
			final String musicName = (String) map.get("title");
			final String playerName = (String) map.get("Artist");
			
			//View view = super.getView(position, convertView, parent);
			TextView musicNameText = (TextView) convertView.findViewById(R.id.musicName);
			TextView playerNameText = (TextView) convertView.findViewById(R.id.playerName);
			musicNameText.setText(musicName);
			playerNameText.setText(playerName);
			
			ImageView imgMore = (ImageView) convertView.findViewById(R.id.moreImg);
			
			//设置弹出菜单
			if(imgMore != null)
			{ 
				//得到弹出菜单， 将Pos储存
				View moreView = (View)convertView.findViewById(R.id.music_more_layout);
				moreView.setTag(position);
				
				//将弹出菜单存到按钮里
				imgMore.setTag(moreView);
				imgMore.setOnClickListener(moreOnClickListener);
				
				//隐藏所有弹出菜单
				moreView.setVisibility(View.GONE);
				if(mLastMore != null)
				{	
					//mLastMore.setVisibility(View.GONE);
					//mLastMore = null;
				}
				
				//添加相关点击
				Button btnAdd = (Button)moreView.findViewById(R.id.native_music_btn_add);
				Button btnDel = (Button)moreView.findViewById(R.id.native_music_btn_del);
				btnAdd.setTag(position);
				btnDel.setTag(position);
				btnAdd.setOnClickListener(AddOnClickListener);
				btnDel.setOnClickListener(DelOnClickListener);
			}
			
			return convertView;
		}
			
			//更多按下
			private View.OnClickListener moreOnClickListener = new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {

					View moreView = (View)v.getTag();
					
					//如果上一次点击了菜单， 隐藏之
					if(mLastMore != null) {
						mLastMore.setVisibility(View.GONE);
					}
					
					//滑动动画
					AnimaAccess anim = new AnimaAccess(NativeMusicActivity.this);
					moreView.startAnimation(anim.alphaAnimation(0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 200, false));
					
					moreView.setVisibility(View.VISIBLE);
					
					//储存这次按下的菜单
					mLastMore = moreView;
				}
			};
			
			// 添加到歌单
			private View.OnClickListener AddOnClickListener = new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					int position = Integer.parseInt(v.getTag().toString());
					
					//moreInterface.OnClickDownload(position);
					
					HashMap<String, Object> map = mp3list.get(position);
					EditListMusicActivty.mp3list = new ArrayList<HashMap<String, Object>>();
					EditListMusicActivty.mp3list.add(map);
					
					EditListMusicActivty.noList = new ArrayList<String>();
					EditListMusicActivty.noList.add(0 + "");
					
					ServerAccess.AddOneMusicToMenu = true;
					ServerAccess.musicMap = map;
					
					Intent intent = new Intent(NativeMusicActivity.this,EditAddTo.class);
					startActivity(intent);
					overridePendingTransition(R.anim.right_in, R.anim.left_out);
					
					mLastMore.setVisibility(View.GONE);
				}
			};
			
			//删除按下
				private View.OnClickListener DelOnClickListener = new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						int position = Integer.parseInt(v.getTag().toString());
						
						dialog(position);
						
						mLastMore.setVisibility(View.GONE);
					}
				};
				
				  protected void dialog(final int position) { 
				        AlertDialog.Builder builder = new Builder(NativeMusicActivity.this); 
				        builder.setMessage("确定要删除该歌曲吗?"); 
				        builder.setTitle("提示"); 
				        builder.setPositiveButton("删除", 
				                 
				                new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {
										ArrayList<String> noList = new ArrayList<String>();
										noList.add(position + "");
										
										//需整改
										for (int i = 0; i < noList.size(); i++) {
											String url = mp3list
													.get(Integer.valueOf(noList.get(i)))
													.get("url").toString();
											File file = new File(url);
											if (sdState.equals(Environment.MEDIA_MOUNTED)) {
												if (file.exists()) {
													if (file.isFile()) {
														// 删除数据库的中数据
														DatabaseUtil databaseUtil = new DatabaseUtil(NativeMusicActivity.this);
														NativeMusicActivity.this
																.getContentResolver()
																.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
																		"_data = ?",
																		new String[] { url });
														file.delete(); // 删除歌曲
														int no = Integer.parseInt(noList
																.get(i));
														mp3list.remove(no); // 删除列表中的数据
														mp3Infos.remove(no);
														databaseUtil.deleteMusic(url);
														MusicPlayer.musicInfos = mp3Infos;
														
														mAdapter.notifyDataSetChanged();
													}
												}
											}
										}
										
										Toast.makeText(NativeMusicActivity.this, "删除成功!",
												Toast.LENGTH_SHORT).show();
									}
				        	
				        }); 
				        builder.setNegativeButton("取消", null); 
				        builder.create().show(); 
				    } 
	}
	
	@Override
	protected void onResume() {
		mAdapter.notifyDataSetChanged();
		super.onRestart();
		
	}

	
}
